package com.lindroy.androidplayer.base

import androidx.lifecycle.ViewModel
import androidx.lifecycle.distinctUntilChanged
import androidx.lifecycle.viewModelScope
import com.lindroy.androidplayer.logic.model.LoginModel
import com.lindroy.androidplayer.utils.SingleLiveEvent
import com.lindroy.androidplayer.utils.mapSingle
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch

/**
 * @author Lin
 * @date 2021/11/8
 * @function 全局 ViewModel，用于处理全局消息
 */
class EventViewModel : ViewModel() {

    private val _loadingLiveData = SingleLiveEvent<Boolean>()

    private val _toastLiveData = SingleLiveEvent<String?>()

    private val _isStatusBarDarkMode = SingleLiveEvent<Boolean>()

    private val _loginInfoFlow = MutableSharedFlow<LoginModel>()

    val loginInfoFlow = _loginInfoFlow.map { it }

    val loadingLiveData = _loadingLiveData.mapSingle { it }

    val toastLiveData = _toastLiveData.mapSingle { it }

    val isStatusBarDarkMode = _isStatusBarDarkMode.mapSingle { it }.distinctUntilChanged()

    fun showLoading() {
        _loadingLiveData.postValue(true)
    }

    fun dismissLoading() {
        _loadingLiveData.postValue(false)
    }

    fun showToast(msg: String?) {
        _toastLiveData.postValue(msg)
    }

    fun postLoginInfo(loginModel: LoginModel) {
        viewModelScope.launch {
            _loginInfoFlow.emit(loginModel)
        }
    }

    fun postStatusBarDarkMode(isDarkMode:Boolean){
//        if (_isStatusBarDarkMode.value == isDarkMode){
//            return
//        }
        _isStatusBarDarkMode.postValue(isDarkMode)
    }
}